<template>
  <div class="chat-container">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h3>聊天记录</h3>
        <el-button type="primary" size="small" @click="createNewChat">
          <el-icon><Plus /></el-icon> 新对话
        </el-button>
      </div>

      <div class="chat-list">
        <div
          v-for="chat in chatList"
          :key="chat.id"
          :class="['chat-item', { active: currentChatId === chat.id }]"
          @click="switchChat(chat.id)"
        >
          <el-avatar :size="40" :src="aiAvatar" />
          <div class="chat-info">
            <div class="chat-title">对话 {{ chat.id }}</div>
            <div class="chat-preview">{{ chat.lastMessage || "新的对话" }}</div>
          </div>
          <div class="chat-time">{{ formatTime(chat.updateTime) }}</div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天主界面 -->
    <div class="chat-main">
      <!-- 聊天记录区域 -->
      <div class="chat-messages" ref="messageContainer">
        <template v-for="(message, index) in messages" :key="index">
          <div :class="['message', message.type]">
            <div class="avatar">
              <el-avatar
                :size="40"
                :src="message.type === 'user' ? userInfo.avatar : aiAvatar"
              />
            </div>
            <div class="content">
              <div class="name">
                {{ message.type === "user" ? userInfo.userName : "AI助手" }}
              </div>
              <div class="text">{{ message.content }}</div>
              <div class="time">{{ formatTime(message.time) }}</div>
            </div>
          </div>
        </template>

        <!-- 等待动画 -->
        <div v-if="loading" class="message ai">
          <div class="avatar">
            <el-avatar :size="40" :src="aiAvatar" />
          </div>
          <div class="content">
            <div class="name">AI助手</div>
            <div class="text typing-indicator">
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          @keydown.enter.prevent="handleEnter"
        />
        <el-button type="primary" :loading="loading" @click="sendMessage">
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { Plus } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import {
  sendChatMessage,
  getChatHistory,
  getChatHistoryById,
  type HistoryMessage,
} from "@/api/chat";
import { ElMessage } from "element-plus";
import { getUserInfo } from "@/api/user";

// 定义聊天会话类型
interface ChatSession {
  id: string;
  lastMessage: string;
  updateTime: Date;
  messages: Message[];
}

// 定义消息类型
interface Message {
  type: "user" | "ai";
  content: string;
  time: Date;
}

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message: string | null;
}

const chatList = ref<ChatSession[]>([]);
const currentChatId = ref<string>("");
const messages = ref<Message[]>([]);
const inputMessage = ref("");
const loading = ref(false);
const messageContainer = ref<HTMLElement | null>(null);

// 头像
const userAvatar = "path/to/user/avatar";
// const aiAvatar = "path/to/ai/avatar";
const aiAvatar = ref("/images/ai-avatar.jpg");

// 问题建议
const suggestions = [
  "附近有什么好玩的景点？",
  "当地有什么特色美食？",
  "如何前往某个景点？",
  "农产品价格如何？",
  "旅游住宿推荐",
];

// 用户信息
interface UserInfo {
  id: number;
  userName: string;
  avatar: string;
  // ... 其他需要的字段
}

const userInfo = ref<UserInfo>({
  id: 0,
  userName: "游客",
  avatar: "",
});

// 格式化时间
const formatTime = (date: Date) => {
  return dayjs(date).format("HH:mm");
};

// 生成六位随机数作为会话ID
function generateChatId(): string {
  return Math.floor(100000 + Math.random() * 900000).toString();
}

// 添加获取历史会话的方法
const fetchChatHistory = async () => {
  try {
    const res = await getChatHistory();
    console.log("获取到的历史会话:", res);

    if (res.success && res.data && Array.isArray(res.data)) {
      // 将每个历史会话ID转换为ChatSession对象
      const historySessions = res.data.map((chatId: string) => ({
        id: chatId,
        lastMessage: "历史会话",
        updateTime: new Date(),
        messages: [],
      }));

      chatList.value = historySessions;

      // 如果有历史会话，选中第一个
      if (historySessions.length > 0) {
        switchChat(historySessions[0].id);
      } else {
        // 如果没有历史会话，创建一个新会话
        createNewChat();
      }
    } else {
      // 如果没有历史会话，创建一个新会话
      createNewChat();
    }
  } catch (error) {
    console.error("获取历史会话失败:", error);
    ElMessage.error("获取历史会话失败");
    // 出错时创建一个新会话
    createNewChat();
  }
};

// 修改组件挂载时的逻辑
onMounted(async () => {
  await fetchUserInfo();
  await fetchChatHistory();

  // 只有在没有历史会话的情况下才创建新会话
  if (chatList.value.length === 0) {
    createNewChat();
    messages.value.push({
      type: "ai",
      content:
        "您好！我是您的智能助手，很高兴为您服务。您可以询问我关于景点、美食、住宿等问题。",
      time: new Date(),
    });
  }
});

// 修改创建新对话的方法
const createNewChat = () => {
  const newChatId = generateChatId();
  const newChat = {
    id: newChatId,
    lastMessage: "新的对话",
    updateTime: new Date(),
    messages: [],
  };

  // 将新会话添加到列表开头
  chatList.value.unshift(newChat);
  currentChatId.value = newChatId;

  // 清空消息列表并添加欢迎消息
  const welcomeMessage = {
    type: "ai" as const,
    content:
      "您好！我是您的智能助手，很高兴为您服务。您可以询问我关于景点、美食、住宿等问题。",
    time: new Date(),
  };

  messages.value = [welcomeMessage];

  // 更新会话信息
  updateChatSession(welcomeMessage);

  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
};

// 修改切换对话的方法
const switchChat = async (chatId: string) => {
  currentChatId.value = chatId;
  loading.value = true;

  try {
    const res = await getChatHistoryById(chatId);
    console.log("获取到的历史消息:", res);
    if (res.success && res.data) {
      // 将后端返回的消息格式转换为前端使用的格式
      messages.value = res.data.map((msg: HistoryMessage) => ({
        type: msg.role === "user" ? "user" : "ai",
        content: msg.content.trim(),
        time: new Date(), // 由于后端没有返回时间，这里暂时使用当前时间
      }));

      // 更新当前会话的最后一条消息预览
      const chatIndex = chatList.value.findIndex((c) => c.id === chatId);
      if (chatIndex > -1 && messages.value.length > 0) {
        const lastMessage = messages.value[messages.value.length - 1];
        chatList.value[chatIndex].lastMessage = lastMessage.content;
        chatList.value[chatIndex].updateTime = lastMessage.time;
      }
    }
  } catch (error) {
    console.error("获取历史消息失败:", error);
    ElMessage.error("获取历史消息失败");
    messages.value = []; // 失败时清空消息列表
  } finally {
    loading.value = false;
    // 切换完成后滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 更新会话列表
const updateChatSession = (message: Message) => {
  const chatIndex = chatList.value.findIndex(
    (c) => c.id === currentChatId.value
  );
  if (chatIndex > -1) {
    const chat = chatList.value[chatIndex];
    chat.lastMessage = message.content;
    chat.updateTime = message.time;
    chat.messages = [...messages.value];

    // 将当前会话移到顶部
    chatList.value.splice(chatIndex, 1);
    chatList.value.unshift(chat);
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value || !currentChatId.value)
    return;

  const message = inputMessage.value.trim();
  inputMessage.value = "";

  const userMessage: Message = {
    type: "user",
    content: message,
    time: new Date(),
  };

  messages.value.push(userMessage);
  updateChatSession(userMessage);

  loading.value = true;

  try {
    const res = await sendChatMessage(message, currentChatId.value);
    console.log("AI回复:", res);

    if (res.success && res.data) {
      const aiMessage: Message = {
        type: "ai",
        content: res.data.trimStart(),
        time: new Date(),
      };
      messages.value.push(aiMessage);
      updateChatSession(aiMessage);
    }
  } catch (error) {
    console.error("错误:", error);
    ElMessage.error("发送消息失败，请重试");
  } finally {
    loading.value = false;
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 使用建议问题
const useQuestion = (question: string) => {
  inputMessage.value = question;
};

// 优化滚动到底部的函数
const scrollToBottom = () => {
  if (!messageContainer.value) return;

  const container = messageContainer.value;
  const isScrolledToBottom =
    container.scrollHeight - container.scrollTop <=
    container.clientHeight + 100;

  if (isScrolledToBottom) {
    container.scrollTop = container.scrollHeight;
  }
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo();
    console.log("获取到的用户信息:", res);
    if (res && res.success && res.data) {
      userInfo.value = {
        id: res.data.id,
        userName: res.data.userName || "游客",
        avatar: res.data.avatar || "",
      };
      console.log("用户信息设置成功:", userInfo.value);
    } else {
      ElMessage.error("获取用户信息失败: " + (res?.message || "未知错误"));
      userInfo.value = {
        id: 0,
        userName: "游客",
        avatar: "/images/ai-avatar.jpg",
      };
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
    userInfo.value = {
      id: 0,
      userName: "游客",
      avatar: "/images/ai-avatar.jpg",
    };
  }
};

// 添加这个方法
const handleEnter = (e: KeyboardEvent) => {
  if (!e.shiftKey) {
    sendMessage();
  }
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 60px);
  background: #f5f7fa;
  padding: 20px;
  gap: 20px;
}

.chat-sidebar {
  width: 300px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
    }
  }

  .chat-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;

    .chat-item {
      display: flex;
      align-items: center;
      padding: 12px;
      border-radius: 8px;
      cursor: pointer;
      margin-bottom: 4px;

      &:hover {
        background: #f5f7fa;
      }

      &.active {
        background: #ecf5ff;
      }

      .chat-info {
        flex: 1;
        margin: 0 12px;
        overflow: hidden;

        .chat-title {
          font-size: 14px;
          margin-bottom: 4px;
        }

        .chat-preview {
          font-size: 12px;
          color: #999;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .chat-time {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;

  .message {
    display: flex;
    margin-bottom: 20px;

    &.ai {
      flex-direction: row;
    }

    &.user {
      flex-direction: row-reverse;

      .content {
        align-items: flex-end;

        .text {
          background: #409eff;
          color: white;
        }
      }
    }

    .avatar {
      margin: 0 12px;
    }

    .content {
      display: flex;
      flex-direction: column;
      max-width: 70%;

      .name {
        font-size: 14px;
        color: #999;
        margin-bottom: 4px;
      }

      .text {
        padding: 12px 16px;
        background: #f4f4f5;
        border-radius: 8px;
        font-size: 14px;
        line-height: 1.5;
      }

      .time {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
      }
    }
  }
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
  align-items: flex-end;

  .el-input {
    flex: 1;
  }

  .el-button {
    height: 78px;
    width: 80px;
  }
}

.loading-text {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 12px 20px !important;

  .dot {
    width: 8px;
    height: 8px;
    background: #666;
    border-radius: 50%;
    animation: dot-flashing 1s infinite linear alternate;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes dot-flashing {
  0% {
    opacity: 0.2;
  }
  100% {
    opacity: 1;
  }
}

.message {
  &.user {
    .avatar {
      .el-avatar {
        background-color: #fff;
      }
    }

    .name {
      text-align: right;
      padding-right: 8px;
      color: #666;
      font-size: 14px;
    }
  }
}

// 可以添加打字机效果的样式
.message.ai .text {
  white-space: pre-wrap;
  word-break: break-word;
}

// 添加打字机效果的动画样式
.typing-indicator {
  background: #f4f4f5 !important;
  padding: 12px 16px !important;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 60px;
  height: 32px;

  .typing-dot {
    width: 8px;
    height: 8px;
    background: #666;
    border-radius: 50%;
    opacity: 0.4;
    animation: typingAnimation 1.4s infinite;

    &:nth-child(1) {
      animation-delay: 0s;
    }

    &:nth-child(2) {
      animation-delay: 0.4s;
    }

    &:nth-child(3) {
      animation-delay: 0.8s;
    }
  }
}

@keyframes typingAnimation {
  0%,
  100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  50% {
    transform: translateY(-4px);
    opacity: 1;
  }
}

// 确保消息内容样式正确
.message.ai .content {
  .text {
    background: #f4f4f5;
    padding: 12px 16px;
    border-radius: 8px;
    font-size: 14px;
    line-height: 1.5;
    white-space: pre-wrap;
    word-break: break-word;
  }
}
</style> 